package com.example.james.uicustomviews;


import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

/**
 * Created by James on 1/25/2018.
 */

public class FruitAdapter extends ArrayAdapter<Fruit> implements AdapterView.OnItemClickListener {

    private int resourceId;

    public FruitAdapter(@NonNull Context context, int resource, @NonNull List<Fruit> objects) {
        super(context, resource, objects);
        resourceId = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Fruit fruit = getItem(position);
//        View view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
        ViewHolder viewHolder;
        View view;
        if (convertView == null){
            view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.fruitImage = view.findViewById(R.id.fruit_image);
            viewHolder.fruitName = view.findViewById(R.id.fruit_name);
            view.setTag(viewHolder);
        } else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }
//        ImageView imageView = view.findViewById(R.id.fruit_image);
//        TextView textView = view.findViewById(R.id.fruit_name);
//        imageView.setImageResource(fruit.getImageId());
//        textView.setText(fruit.getName());
        viewHolder.fruitName.setText(fruit.getName());
        viewHolder.fruitImage.setImageResource(fruit.getImageId());
        return view;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Fruit fruit = getItem(i);
        Toast.makeText(getContext(), fruit.getName(), Toast.LENGTH_LONG).show();
    }

    class ViewHolder{
        ImageView fruitImage;
        TextView fruitName;
    }
}
